package com.example.demoback.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demoback.common.Constants;
import com.example.demoback.entity.People;
import com.example.demoback.exception.ServiceException;
import com.example.demoback.service.IPeopleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//拦截器拦截token
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private IPeopleService iPeopleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token"); //获取请求头

//是否需要验证
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        } else {
//            HandlerMethod h = (HandlerMethod) handler;
//            AuthAccess authAccess = h.getMethodAnnotation(AuthAccess.class);
//            if (authAccess != null) {
//                return true;
//            }
        }
//验证请求头的token是否为空
        // 执行认证
        if (StrUtil.isBlank(token)) { //token为空
            throw new ServiceException(Constants.CODE_401, "无token，请重新登录");
        }
        // 获取 token 中的 user id，验证是否存在id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException(Constants.CODE_401, "token验证失败，请重新登录");
        }

//验证当前是否存在登录用户
        // 根据token中的userid查询数据库
        QueryWrapper<People> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("peopleids",userId);
        People people = iPeopleService.getOne(queryWrapper);
        if (people == null) {
            throw new ServiceException(Constants.CODE_401, "用户不存在，请重新登录");
        }
//验证token正确性
        // 用户密码加签验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(people.getPeoplepassword())).build();
        try {
            jwtVerifier.verify(token); // 验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.CODE_401, "token验证失败，请重新登录");
        }
        return true;
    }
}
